package main.java.web.servlet;

import main.java.domain.Task;
import main.java.domain.User;
import main.java.service.TaskService;
import main.java.service.UserService;
import main.java.service.impl.TaskServiceImpl;
import main.java.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");

        // 获取数据
        Map<String, String[]> map = request.getParameterMap();

        // 封装user
        User loginUser = new User();
        try {
            BeanUtils.populate(loginUser, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        // 调用service查询
        UserService service = new UserServiceImpl();
        User user = service.login(loginUser);

        // 判断登录是否成功
        if (user != null) {
            request.removeAttribute("msg");
            // 将用户存入session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 将tasks存入session
            TaskService taskService = new TaskServiceImpl();
            List<Task> tasks = taskService.findAll(user.getId(), user.getType());

            session.setAttribute("tasks", tasks);
            // 重定向

            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            request.setAttribute("msg", "用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
